<template>
  <div class="policy-management-container">
    <!-- 搜索和筛选区域（仅保留保单号模糊查询） -->
    <el-card class="filter-card mb-6 shadow-md hover:shadow-lg transition-shadow duration-300">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="保单编号" class="w-[300px]">
          <el-input
              v-model="searchForm.policyId"
              placeholder="请输入保单编号（模糊查询）"
              clearable
              size="small"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              size="small"
              @click="handleSearch"
              class="mr-2"
          >
            <i class="el-icon-search mr-1"></i>查询
          </el-button>
          <el-button
              size="small"
              @click="resetSearch"
          >
            <i class="el-icon-refresh mr-1"></i>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 投保单列表（仅显示待缴费数据） -->
    <el-card class="policy-table-card shadow-md">
      <div class="table-container">
        <el-table
            :data="policyList"
            border
            stripe
            v-loading="loading"
            element-loading-text="加载中，请稍候..."
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
            style="width: 100%"
        >
          <el-table-column
              prop="policyId"
              label="保单编号"
              width="180"
              align="center"
              fixed="left"
          ></el-table-column>
          <el-table-column
              prop="insuredId"
              label="投保人ID"
              width="140"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="insuranceCoverageName"
              label="保险类型"
              width="140"
              align="center"
          ></el-table-column>
          <el-table-column
              label="承保数量"
              width="120"
              align="center"
              :formatter="formatCoverageQuantity"
          ></el-table-column>
          <el-table-column
              prop="startDate"
              label="保险起期"
              width="120"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="endDate"
              label="保险止期"
              width="120"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="sumInsured"
              label="总保额(元)"
              width="110"
              align="right"
          ></el-table-column>
          <el-table-column
              prop="totalPremium"
              label="总保费(元)"
              width="110"
              align="right"
          ></el-table-column>
          <!-- 缴费状态列（固定显示待缴费） -->
          <el-table-column
              prop="payStatus"
              label="缴费状态"
              width="100"
              align="center"
          >
            <template #default="scope">
              <span class="text-orange-500">待缴费</span>
            </template>
          </el-table-column>
          <!-- 保单状态列 -->
          <el-table-column
              prop="policyStatus"
              label="保单状态"
              width="100"
              align="center"
          >
            <template #default="scope">
              <el-tag
                  :type="getStatusTagType(scope.row.policyStatus)"
                  :class="scope.row.policyStatus === 3 ? 'bg-red-500' : ''"
                  class="cursor-default"
              >
                {{ formatPolicyStatus(scope.row.policyStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
              prop="createTime"
              label="投保时间"
              width="160"
              align="center"
          ></el-table-column>
          <!-- 操作列（仅保留详情+支付按钮） -->
          <el-table-column
              label="操作"
              width="200"
              fixed="right"
              align="center"
          >
            <template #default="scope">
              <!-- 详情按钮 -->
              <el-button
                  type="text"
                  size="small"
                  @click="handleViewDetail(scope.row.orderId)"
                  class="text-blue-600 hover:text-blue-800 transition-colors mr-3"
              >
                <i class="el-icon-view mr-1"></i>详情
              </el-button>

              <!-- 支付操作按钮（暂不调用接口） -->
              <el-button
                  type="primary"
                  size="small"
                  @click="handlePay(scope.row)"
                  class="bg-green-600 hover:bg-green-700 transition-colors"
              >
                <i class="el-icon-money mr-1"></i>去支付
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页控件 -->
      <div class="pagination-container mt-4 flex justify-end items-center">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            background
        ></el-pagination>
      </div>
    </el-card>

    <!-- 详情弹窗（仅查看，移除状态修改功能） -->
    <el-dialog
        title="投保单详情（待缴费）"
        v-model="detailDialogVisible"
        width="600px"
        :close-on-click-modal="false"
        :before-close="handleDetailDialogClose"
    >
      <div class="detail-container" v-loading="detailLoading">
        <!-- 基础信息区域 -->
        <div class="detail-section mb-4">
          <h3 class="section-title text-lg font-semibold mb-3">基础信息</h3>
          <el-form :model="currentPolicy" label-width="120px" class="detail-form">
            <el-form-item label="保单编号">
              <el-input v-model="currentPolicy.policyId" disabled></el-input>
            </el-form-item>
            <el-form-item label="投保人ID">
              <el-input v-model="currentPolicy.insuredId" disabled></el-input>
            </el-form-item>
            <el-form-item label="保险类型">
              <el-input v-model="currentPolicy.insuranceCoverageName" disabled></el-input>
            </el-form-item>
            <el-form-item label="投保项目">
              <el-input v-model="currentPolicy.insuranceSubject" disabled></el-input>
            </el-form-item>
          </el-form>
        </div>

        <!-- 承保信息区域 -->
        <div class="detail-section mb-4">
          <h3 class="section-title text-lg font-semibold mb-3">承保信息</h3>
          <el-form :model="currentPolicy" label-width="120px" class="detail-form">
            <el-form-item label="承保面积(亩)" v-if="currentPolicy.coverageArea">
              <el-input v-model="currentPolicy.coverageArea" disabled></el-input>
            </el-form-item>
            <el-form-item label="承保数量(头/只)" v-if="currentPolicy.coverageQuantity">
              <el-input v-model="currentPolicy.coverageQuantity" disabled></el-input>
            </el-form-item>
            <el-form-item label="单位保额(元)">
              <el-input v-model="currentPolicy.unitInsured" disabled></el-input>
            </el-form-item>
            <el-form-item label="总保额(元)">
              <el-input v-model="currentPolicy.sumInsured" disabled></el-input>
            </el-form-item>
            <el-form-item label="总保费(元)">
              <el-input v-model="currentPolicy.totalPremium" disabled></el-input>
            </el-form-item>
          </el-form>
        </div>

        <!-- 时间与状态区域（仅查看，无编辑） -->
        <div class="detail-section mb-4">
          <h3 class="section-title text-lg font-semibold mb-3">时间与状态</h3>
          <el-form :model="currentPolicy" label-width="120px" class="detail-form">
            <el-form-item label="保险起期">
              <el-input v-model="currentPolicy.startDate" disabled></el-input>
            </el-form-item>
            <el-form-item label="保险止期">
              <el-input v-model="currentPolicy.endDate" disabled></el-input>
            </el-form-item>
            <el-form-item label="缴费状态">
              <el-input value="待缴费" disabled class="text-orange-500"></el-input>
            </el-form-item>
            <el-form-item label="保单状态">
              <el-input :value="formatPolicyStatus(currentPolicy.policyStatus)" disabled></el-input>
            </el-form-item>
            <el-form-item label="投保时间">
              <el-input v-model="currentPolicy.createTime" disabled></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 弹窗底部按钮（仅关闭） -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 支付提示弹窗（暂不调用接口，仅提示） -->
    <el-dialog
        title="支付提示"
        v-model="payDialogVisible"
        width="350px"
        :close-on-click-modal="false"
    >
      <div class="text-center py-4">
        <i class="el-icon-info text-blue-500 text-4xl mb-3"></i>
        <p class="mb-2">当前为演示模式，暂不发起实际支付</p>
        <p class="text-gray-500 text-sm">保单编号：{{ currentPayPolicyId }}</p>
        <p class="text-gray-500 text-sm">需支付金额：{{ currentPayAmount }} 元</p>
      </div>
      <div slot="footer" class="dialog-footer flex justify-center">
        <el-button @click="payDialogVisible = false">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, nextTick} from 'vue';
import {ElMessage, ElLoading} from 'element-plus';
import hxxp from "@/utils/hxxp";

// 状态管理（确保变量只声明一次）
const policyList = ref([]);
const loading = ref(false);
const detailLoading = ref(false);
const detailDialogVisible = ref(false);
const payDialogVisible = ref(false);
const payLoading = ref(false);

// 当前操作数据
const currentOrderId = ref(null);
const currentPolicy = ref({
  orderId: '',
  policyId: '',
  insuredId: '',
  insuranceCoverageName: '',
  insuranceSubject: '',
  coverageArea: '',
  coverageQuantity: '',
  unitInsured: '',
  sumInsured: '',
  totalPremium: '',
  startDate: '',
  endDate: '',
  policyStatus: '',
  createTime: ''
});
const currentPayPolicyId = ref('');
const currentPayAmount = ref(0);

// 搜索表单
const searchForm = reactive({
  policyId: ''
});

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
});

// 页面加载时获取列表
onMounted(() => {
  fetchPolicyList();
});

// 获取待缴费保单列表
const fetchPolicyList = () => {
  loading.value = true;
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    policyId: searchForm.policyId,
    payStatus: 1
  };

  hxxp.get('/aiInsureOrder/list', {params})
      .then(response => {
        loading.value = false;
        if (response.code === 100200) {
          policyList.value = response.data.list;
          pagination.total = response.data.total;
        } else {
          ElMessage.error(response.msg || '查询待缴费保单失败');
        }
      })
      .catch(error => {
        loading.value = false;
        console.error('查询失败', error);
        ElMessage.error('网络异常，查询失败');
      });
};

// 搜索和重置
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchPolicyList();
};

const resetSearch = () => {
  searchForm.policyId = '';
  pagination.currentPage = 1;
  fetchPolicyList();
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchPolicyList();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchPolicyList();
};

// 格式化函数
const formatCoverageQuantity = (row) => {
  if (row.coverageArea) {
    return `${Number(row.coverageArea).toFixed(2)} 亩`;
  } else if (row.coverageQuantity) {
    return `${row.coverageQuantity} 头/只`;
  }
  return '-';
};

const formatPolicyStatus = (status) => {
  const statusMap = {
    1: '待生效',
    2: '已生效',
    3: '已退保',
    4: '已过期'
  };
  return statusMap[status] || '未知状态';
};

const getStatusTagType = (status) => {
  const typeMap = {
    1: 'warning',
    2: 'success',
    3: 'danger',
    4: 'info'
  };
  return typeMap[status] || 'default';
};

// 详情弹窗
const handleViewDetail = (orderId) => {
  if (!orderId) {
    ElMessage.error('缺少保单ID，无法查看详情');
    return;
  }

  currentOrderId.value = orderId;
  detailLoading.value = true;

  hxxp.get(`/aiInsureOrder/get/${orderId}`)
      .then(response => {
        detailLoading.value = false;
        if (response.code === 100200) {
          const policyData = response.data;
          currentPolicy.value = {
            ...policyData,
            insuranceSubject: policyData.insuranceSubject || '未填写',
            coverageArea: policyData.coverageArea ? Number(policyData.coverageArea).toFixed(2) : '',
            coverageQuantity: policyData.coverageQuantity || '0',
            unitInsured: Number(policyData.unitInsured || 0).toFixed(2),
            sumInsured: Number(policyData.sumInsured || 0).toFixed(2),
            totalPremium: Number(policyData.totalPremium || 0).toFixed(2)
          };
          nextTick(() => {
            detailDialogVisible.value = true;
          });
        } else {
          ElMessage.error(response.msg || '获取保单详情失败');
        }
      })
      .catch(error => {
        detailLoading.value = false;
        console.error('获取详情失败', error);
        ElMessage.error('网络异常，获取详情失败');
      });
};

const handleDetailDialogClose = () => {
  detailDialogVisible.value = false;
  currentOrderId.value = null;
  currentPolicy.value = {};
};

// 支付按钮逻辑（修正语法错误）
const handlePay = async (row) => {
  // 参数校验
  if (!row || !row.policyId || !row.totalPremium) {
    ElMessage.error('支付信息不完整（缺少保单号或金额）');
    return;
  }

  // 显示加载中
  const payLoadingInstance = ElLoading.service({
    lock: true,
    text: '正在发起支付，请稍候...',
    background: 'rgba(255, 255, 255, 0.7)'
  });
  console.log(hxxp.defaults.baseURL);
  try {
    // 构造支付接口地址
    const payUrl = `${hxxp.defaults.baseURL}/aiPay/pay`;
    const queryParams = new URLSearchParams({
      policyId: row.policyId,
      paymentAmount: row.totalPremium.toString()
    });
    // const response = await hxxp.get('/aiPay/pay', { queryParams })
    // 跳转支付
    window.location.href = `${payUrl}?${queryParams.toString()}`;
  } catch (error) {
    console.error('发起支付异常：', error);
    ElMessage.error('网络异常，发起支付失败，请稍后重试');
  } finally {
    // 关闭加载提示（即使跳转，也需要确保资源释放）
    payLoadingInstance.close();
  }
};
</script>

<style scoped>
.policy-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  overflow: auto;
}

/* 弹窗层级优化 */
::v-deep .el-dialog {
  z-index: 9999 !important;
}

::v-deep .el-dialog__wrapper {
  z-index: 9999 !important;
}

.filter-card {
  border-radius: 8px;
  overflow: hidden;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.table-container {
  overflow-x: auto;
}

.pagination-container {
  padding: 10px 0;
}

/* 详情弹窗样式 */
.detail-container {
  padding: 10px 0;
}

.detail-section {
  border-bottom: 1px dashed #e5e7eb;
  padding-bottom: 15px;
}

.section-title {
  color: #333;
  border-left: 4px solid #409eff;
  padding-left: 8px;
}

.detail-form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

/* 支付按钮样式 */
::v-deep .el-button.bg-green-600 {
  background-color: #22c55e !important;
  border-color: #22c55e !important;
}

::v-deep .el-button.bg-green-600:hover {
  background-color: #16a34a !important;
  border-color: #16a34a !important;
}

::v-deep .el-tag.bg-red-500 {
  background-color: #f56c6c !important;
  border-color: #f56c6c !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .detail-form {
    grid-template-columns: 1fr;
  }

  .policy-management-container {
    padding: 10px;
  }

  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .el-form-item {
    width: 100% !important;
  }

  .pagination-container {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
}

@media (max-width: 1200px) {
  .search-form {
    gap: 8px;
  }

  .el-form-item {
    margin-bottom: 10px !important;
  }
}
</style>
